package com.example.dishit.model.dbproxy;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.dishit.model.dbproxy.data.Dish;
import com.example.dishit.model.dbproxy.data.Restaurant;
import com.example.dishit.model.dbproxy.data.Review;
import com.example.dishit.model.dbproxy.data.UserInfo;

public class DBProxyUtils {

	private static final String BASE_URL = "http://www.cise.ufl.edu/~";
	private static final String CISE_USERNAME = "charan/";
	private static final String SERVER_DIR = "DishIt/";
	private static final String SERVER_SCRIPT = "server.php";
	private static final String SERVER_URL = BASE_URL + CISE_USERNAME
			+ SERVER_DIR + SERVER_SCRIPT;

	private static DefaultHttpClient httpClient = new DefaultHttpClient();

	public static String addFriend(String me, String friend) {
		String responseMessage = "";
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("action", "follow"));
			nameValuePairs.add(new BasicNameValuePair("me", me));
			nameValuePairs.add(new BasicNameValuePair("friend", friend));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (IOException e) {
			post.abort();
			e.printStackTrace();
		}
		String result = "";
		try {
			JSONObject response = new JSONObject(responseMessage);
			result = response.getString("result");
			// System.out.println(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String removeFriend(String me, String friend) {
		String responseMessage = "";
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("action", "remove"));
			nameValuePairs.add(new BasicNameValuePair("me", me));
			nameValuePairs.add(new BasicNameValuePair("friend", friend));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (IOException e) {
			post.abort();
			e.printStackTrace();
		}
		String result = "";
		try {
			JSONObject response = new JSONObject(responseMessage);
			result = response.getString("result");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static List<String> getFriends(String me) {
		String responseMessage = "";
		List<String> friendList = new ArrayList<String>();
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("action", "getFriends"));
			nameValuePairs.add(new BasicNameValuePair("me", me));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (IOException e) {
			post.abort();
			e.printStackTrace();
		}
		try {
			JSONObject response = new JSONObject(responseMessage);
			JSONArray friends = new JSONArray(response.getString("result"));
			for (int i = 0; i < friends.length(); i++) {
				friendList.add(friends.getJSONObject(i).getString("username"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return friendList;
	}

	public static String broadcastDish(Dish dish, byte[] image) {
		String responseMessage = "";
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			MultipartEntity multipart = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			multipart.addPart("Dish", new StringBody(dish.getJSON(),
					"application/json", Charset.forName("UTF-8")));
			if (image != null) {
				// ContentBody imageFile = new FileBody(image, "image/jpeg");
				ContentBody imageFile = new ByteArrayBody(image, "image/png");
				multipart.addPart("Image", imageFile);
			}
			post.setEntity(multipart);
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String result = "";
		try {
			JSONObject response = new JSONObject(responseMessage);
			result = response.getString("result");
			// System.out.println(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String storeReceivedDish(Dish dish, File image) {
		String responseMessage = "";
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			MultipartEntity multipart = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			multipart.addPart("Store", new StringBody(dish.getJSON(),
					"application/json", Charset.forName("UTF-8")));
			if (image != null) {
				ContentBody imageFile = new FileBody(image, "image/jpeg");
				multipart.addPart("Image", imageFile);
			}
			post.setEntity(multipart);
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String result = "";
		try {
			JSONObject response = new JSONObject(responseMessage);
			result = response.getString("result");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static List<Dish> getSentDishes(String me) {
		String responseMessage = "";
		List<Dish> dishList = new ArrayList<Dish>();
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("action", "getMyDishes"));
			nameValuePairs.add(new BasicNameValuePair("me", me));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (IOException e) {
			post.abort();
			e.printStackTrace();
		}
		try {
			JSONObject response = new JSONObject(responseMessage);
			JSONArray dishes = new JSONArray(response.getString("result"));
			for (int i = 0; i < dishes.length(); i++) {
				Dish dish = Dish.buildFromJSON(dishes.getJSONObject(i));
				dishList.add(dish);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return dishList;
	}

	public static List<Dish> getReceivedDishes(String me) {
		String responseMessage = "";
		List<Dish> dishList = new ArrayList<Dish>();
		HttpPost post = new HttpPost(SERVER_URL);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("action",
					"getMyFollowsDishes"));
			nameValuePairs.add(new BasicNameValuePair("me", me));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse getResponse = httpClient.execute(post);
			HttpEntity getResponseEntity = getResponse.getEntity();
			if (getResponseEntity != null) {
				responseMessage = EntityUtils.toString(getResponseEntity);
			}
		} catch (IOException e) {
			post.abort();
			e.printStackTrace();
		}
		try {
			JSONObject response = new JSONObject(responseMessage);
			JSONArray dishes = new JSONArray(response.getString("result"));
			for (int i = 0; i < dishes.length(); i++) {
				Dish dish = Dish.buildFromJSON(dishes.getJSONObject(i));
				dishList.add(dish);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return dishList;
	}

	public static void main(String[] args) {
		// DBProxy proxy;
		UserInfo me = UserInfo.GetUserInfoObject("charan", "charan");
		// UserInfo friend = UserInfo.GetUserInfoObject("friend", "friend");
		// DBProxy.createUser(me);
		// DBProxy.authenticateUser(me);
		// DBProxy.createUser(friend);
		// DBProxy.addFriend("charan", "friend");
		Dish dish = new Dish(new Review(new Restaurant("Starbucks",
				"SW 34TH ST", "Gainesville", "FL", 32608), "5comments", 3.5f),
				me.getUserName());
		// Dish dish = new Dish(new Review(new Restaurant("Panera Bread",
		// "Fayettville Road", "Durham", "NC", 22756), "comments", 2.5f),
		// friend.getUserName());

		// FIXME: change File to a byte-array.
		// DBProxyUtils.broadcastDish(dish, new File("Tulips.jpg"));

		// DBProxy.getMyDishes(me.getUserName());
		// DBProxy.getFollowsDishes(me.getUserName());
		// DBProxy.broadcastDishWithImage(dish, new File("Tulips.jpg"));
		// DBProxy.broadcastDishWithImage(dish, new File("Tulips.jpg"));
		// DBProxy.broadcastDishWithImage(dish, null);
		// String str =
		// "http:\\\\www.cise.ufl.edu\\~charan\\DBService\\images\\1365976051Tulips.jpg";
		// System.out.println(str);
	}
}
